package com.dlc.shop.common.config.aof;

import cn.hutool.core.util.StrUtil;
import com.dlc.shop.common.bo.AofRedisBO;
import com.dlc.shop.common.exception.YamiShopBindException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * 多个redis管理
 * @author LGH
 */
@Component
public class AofRedisConfig implements DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(AofRedisConfig.class);

    private final StringRedisTemplate stringRedisTemplate;

    private final RedissonClient redissonClient;

    public AofRedisConfig(AofRedisBO aofRedisBO) {

        if (StrUtil.isBlank(aofRedisBO.getRedisAddr())) {
            throw new YamiShopBindException("请在yml配置好 aofRedis 的配置，见 com.dlc.shop.common.bo.AofRedisBO");
        }

        Config config = new Config();

        SingleServerConfig singleServerConfig = config.useSingleServer();
        if (StrUtil.isNotBlank(aofRedisBO.getPassword())) {
            singleServerConfig.setPassword(aofRedisBO.getPassword());
        }
        if (aofRedisBO.getDatabase() != null) {
            singleServerConfig.setDatabase(aofRedisBO.getDatabase());
        } else {
            singleServerConfig.setDatabase(0);
        }
        singleServerConfig.setAddress("redis://" + aofRedisBO.getRedisAddr());

        redissonClient = Redisson.create(config);
        LOGGER.info("创建redisson, redisson={}", redissonClient);

        stringRedisTemplate = new StringRedisTemplate();

        stringRedisTemplate.setValueSerializer(StringRedisSerializer.UTF_8);
        stringRedisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);
        stringRedisTemplate.setConnectionFactory(new RedissonConnectionFactory(redissonClient));

        stringRedisTemplate.afterPropertiesSet();
    }


    public StringRedisTemplate getStringRedisTemplate() {
        return stringRedisTemplate;
    }

    @Override
    public void destroy() throws Exception {
        LOGGER.info("关闭redissonClient, redissonClient={}", redissonClient);
        redissonClient.shutdown();
    }
}
